/**
 * 
 */
package com.flashdeck.domain;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.io.IOUtils;
import org.xml.sax.SAXException;

/**
 * @author Vincentas
 *
 */
public class Deck {
	
	private DeckInfo deckInfo;
	
	private List<Card> cards;
	
	private File deckFile;
	
	private Set<String> tags;
	
	private static final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
	
	private static DeckHandler getDeckHandler(File file) {
		DeckHandler deckHandler = new DeckHandler();
		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			ZipInputStream zis = null;
			try {
				zis = new ZipInputStream(fis);
				
				ZipEntry nextEntry;
				while (zis.available() > 0 && (nextEntry = zis.getNextEntry()) != null) {
					if (nextEntry.getName().equalsIgnoreCase("deck.xml")) {						
						SAXParser parser = parserFactory.newSAXParser();
						parser.parse(zis, deckHandler);						
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} finally {
				IOUtils.closeQuietly(zis);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fis);
		}
		
		return deckHandler;
	}
	
	public static Deck parseDeck(File file) {
		return getDeckHandler(file).getDeck();
	}
	
	public static DeckInfo parseDeckInfo(File file) {
		return getDeckHandler(file).getDeckInfo();
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return getDeckInfo().getName();
	}
	
	/**
	 * @return the cards
	 */
	public List<Card> getCards() {
		return cards;
	}

	/**
	 * @param cards the cards to set
	 */
	public void setCards(List<Card> cards) {
		this.cards = cards;
	}

	/**
	 * @return the deckInfo
	 */
	public DeckInfo getDeckInfo() {
		return deckInfo;
	}

	/**
	 * @param deckInfo the deckInfo to set
	 */
	public void setDeckInfo(DeckInfo deckInfo) {
		this.deckInfo = deckInfo;
	}	
	
	
}
